package com.polaris.live.utils

import android.net.Uri
import com.google.common.cache.CacheBuilder
import com.polaris.live.common.constant.PagConst
import com.polaris.live.common.ext.dp
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.resp.bean.decoration.AbstractDecorationExtBean
import com.polaris.live.resp.bean.decoration.CarAnimationLayersDto
import com.polaris.live.resp.bean.decoration.EmptyDecorationExtBean
import com.polaris.live.resp.bean.decoration.UserDecorationAvatarFrameExtBean
import com.polaris.live.resp.bean.decoration.UserDecorationChatBubbleExtBean
import com.polaris.live.resp.bean.decoration.UserDecorationLiveCarExtBean
import com.polaris.live.resp.bean.decoration.UserDecorationLiveEffectExtBean
import com.polaris.live.resp.bean.decoration.UserDecorationProfileBackgroundExtBean
import java.util.concurrent.TimeUnit

/**
 * 装饰器工具类
 *
 * @author Created by lucas on 2024/2/18 02:00
 */
object DecorationUtils {

    val decorationCache = CacheBuilder.newBuilder()
        .maximumSize(100)
        .expireAfterWrite(30, TimeUnit.MINUTES)
        .build<String, AbstractDecorationExtBean>()

    /**
     * 获取聊天气泡装饰器
     */
    fun getDecorationChatBubble(url: String?): UserDecorationChatBubbleExtBean? {
        if (url.isNullOrEmpty()) return null

        return getDecoration(url)
    }

    /**
     * 获取进场特效装饰器
     */
    fun getDecorationLiveEffect(url: String?): UserDecorationLiveEffectExtBean? {
        if (url.isNullOrEmpty()) return null

        return getDecoration(url)
    }

    /**
     * 获取进场座驾装饰器
     */
    fun getDecorationLiveCar(url: String?): UserDecorationLiveCarExtBean? {
        if (url.isNullOrEmpty()) return null

        return getDecoration(url)
    }

    /**
     * 获取用户卡片背景装饰器
     */
    fun getDecorationProfileBackground(url: String?): UserDecorationProfileBackgroundExtBean? {
        if (url.isNullOrEmpty()) return null

        return getDecoration(url)
    }

    /**
     * 获取装饰器
     */
    inline fun <reified T : AbstractDecorationExtBean> getDecoration(url: String): T? {
        val clazz = T::class
        val bean = try {
            decorationCache.get(clazz.simpleName + ":" + url) {
                when (clazz) {
                    UserDecorationAvatarFrameExtBean::class -> {
                        parseUserDecorationAvatarFrameExt(url)
                    }

                    UserDecorationChatBubbleExtBean::class -> {
                        parseUserDecorationChatBubbleExt(url)
                    }

                    UserDecorationLiveEffectExtBean::class -> {
                        parseUserDecorationLiveEffectExt(url)
                    }

                    UserDecorationLiveCarExtBean::class -> {
                        parseUserDecorationLiveCarExt(url)
                    }

                    UserDecorationProfileBackgroundExtBean::class -> {
                        parseUserDecorationProfileBackgroundExt(url)
                    }

                    else -> {
                        EmptyDecorationExtBean
                    }
                }
            }
        } catch (_: Throwable) {
            return null
        }
        if (bean == EmptyDecorationExtBean) {
            return null
        }

        if (bean is T) {
            return bean
        }

        return null
    }

    /**
     * 解析数据
     * "static/decoration/avatar-frame/rich_test.png?width=400&height=400&left=20&top=20&right=20&bottom=80"
     */
    fun parseUserDecorationAvatarFrameExt(url: String): UserDecorationAvatarFrameExtBean? {
        try {
            val regex = Regex("""([^?]+)\?(.+)""")
            val matchResult = regex.matchEntire(url) ?: return null

            val path = matchResult.groupValues[1]
            val query = matchResult.groupValues[2]

            val queryParameters = query.split("&")
                .map { it.split("=") }
                .associateBy({ it[0] }, { it.getOrNull(1) ?: "" })

            return UserDecorationAvatarFrameExtBean(
                url = path,
                width = queryParameters["width"]?.toIntOrNull() ?: 0,
                height = queryParameters["height"]?.toIntOrNull() ?: 0,
                left = queryParameters["left"]?.toIntOrNull() ?: 0,
                top = queryParameters["top"]?.toIntOrNull() ?: 0,
                right = queryParameters["right"]?.toIntOrNull() ?: 0,
                bottom = queryParameters["bottom"]?.toIntOrNull() ?: 0
            )
        } catch (e: Exception) {
            return null
        }
    }

    /**
     * 解析数据
     * "static/decoration/chat-bubble/test.9.png?width=193&height=166&left=20&top=20&right=20&bottom=20&leftBubble=_left&rightBubble=_right&color=#000000"
     */
    fun parseUserDecorationChatBubbleExt(url: String): UserDecorationChatBubbleExtBean? {
        try {
            val regex = Regex("""([^?]+)\?(.+)""")
            val matchResult = regex.matchEntire(url) ?: return null

            val path = matchResult.groupValues[1]

            val query = matchResult.groupValues[2]

            val queryParameters = query.split("&")
                .map { it.split("=") }
                .associateBy({ it[0] }, { it.getOrNull(1) ?: "" })

            return UserDecorationChatBubbleExtBean(
                url = path,
                width = queryParameters["width"]?.toIntOrNull() ?: 0,
                height = queryParameters["height"]?.toIntOrNull() ?: 0,
                left = queryParameters["left"]?.toIntOrNull() ?: 0,
                top = queryParameters["top"]?.toIntOrNull() ?: 0,
                right = queryParameters["right"]?.toIntOrNull() ?: 0,
                bottom = queryParameters["bottom"]?.toIntOrNull() ?: 0,
                leftBubble = queryParameters["leftBubble"] ?: "_left",
                rightBubble = queryParameters["rightBubble"] ?: "_right",
                leftColor = queryParameters["leftColor"] ?: "#000000",
                rightColor = queryParameters["rightColor"] ?: "#FFFFFF",
                translationUrl = queryParameters["translationUrl"],
                lineColor = queryParameters["lineColor"] ?: "#65ffffff"
            )
        } catch (e: Exception) {
            return null
        }
    }

    /**
     * 解析数据
     * "static/decoration/chat-bubble/test.9.png?width=193&height=166&left=20&top=20&right=20&bottom=20&leftBubble=_left&rightBubble=_right&color=#000000"
     */
    fun parseUserDecorationLiveEffectExt(url: String): UserDecorationLiveEffectExtBean? {
        try {
            val regex = Regex("""([^?]+)\?(.+)""")
            val matchResult = regex.matchEntire(url) ?: return null

            val path = matchResult.groupValues[1]
            val query = matchResult.groupValues[2]

            val queryParameters = query.split("&")
                .map { it.split("=") }
                .associateBy({ it[0] }, { it.getOrNull(1) ?: "" })

            return UserDecorationLiveEffectExtBean(
                url = path,
                width = ((queryParameters["width"]?.toIntOrNull() ?: 0) / 3).dp,
                height = ((queryParameters["height"]?.toIntOrNull() ?: 0) / 3).dp,
                left = ((queryParameters["left"]?.toIntOrNull() ?: 0) / 3).dp,
                top = ((queryParameters["top"]?.toIntOrNull() ?: 0) / 3).dp,
                right = ((queryParameters["right"]?.toIntOrNull() ?: 0) / 3).dp,
                bottom = ((queryParameters["bottom"]?.toIntOrNull() ?: 0) / 3).dp,
                color = queryParameters["color"] ?: "#000000",
            )
        } catch (e: Exception) {
            return null
        }
    }

    /**
     * 解析数据
     * "static/decoration/chat-bubble/test.9.png?width=193&height=166&left=20&top=20&right=20&bottom=20&leftBubble=_left&rightBubble=_right&color=#000000"
     */
    fun parseUserDecorationLiveCarExt(url: String): UserDecorationLiveCarExtBean? {
        try {
            val regex = Regex("""([^?]+)\?(.+)""")
            val matchResult = regex.matchEntire(url) ?: return null

            val path = matchResult.groupValues[1]
            val query = matchResult.groupValues[2]

            val queryParameters = query.split("&")
                .map { it.split("=") }
                .associateBy({ it[0] }, { it.getOrNull(1) ?: "" })

            val bean = queryParameters["layers"]?.let { json ->
                JsonUtils.fromJson<CarAnimationLayersDto>(Uri.decode(json))
            }
            return UserDecorationLiveCarExtBean(
                0,
                url = path,
                width = ((queryParameters["width"]?.toIntOrNull() ?: 0) / 3).dp,
                height = ((queryParameters["height"]?.toIntOrNull() ?: 0) / 3).dp,
                gravity = queryParameters["gravity"]?.toIntOrNull() ?: 1,
                duration = 0L,
                soundEffect = Uri.decode(queryParameters["soundEffect"]),
                layers = bean,
            )
        } catch (e: Exception) {
            return null
        }
    }

    /**
     * 解析数据
     * "static/decoration/chat-bubble/test.9.png?width=193&height=166&left=20&top=20&right=20&bottom=20&leftBubble=_left&rightBubble=_right&color=#000000"
     */
    fun parseUserDecorationProfileBackgroundExt(url: String): UserDecorationProfileBackgroundExtBean? {
        try {
            val regex = Regex("""([^?]+)\?(.+)""")
            val matchResult = regex.matchEntire(url) ?: return null

            val path = matchResult.groupValues[1]
            val query = matchResult.groupValues[2]

            val queryParameters = query.split("&")
                .map { it.split("=") }
                .associateBy({ it[0] }, { it.getOrNull(1) ?: "" })

            return UserDecorationProfileBackgroundExtBean(
                url = path,
                width = ((queryParameters["width"]?.toIntOrNull() ?: 0) / 3).dp,
                height = ((queryParameters["height"]?.toIntOrNull() ?: 0) / 3).dp,
                top = ((queryParameters["top"]?.toIntOrNull() ?: 132) / 3).dp,
                pag = if (path.endsWith(PagConst.PAG)) 1 else 0,
            )
        } catch (e: Exception) {
            return null
        }
    }
}